<template>
  <div>
    <search-pane
      :show="showSearchPane"
      @search="handleSearchDeviceRecord"
      @reset="resetDeviceRecordQueryParams"
    >
      <search-item>
        <PDInput
          v-model="queryParams.deviceId"
          input-width="200px"
          description="设备编号"
        />
      </search-item>
      <search-item>
        <PDInput
          v-model="queryParams.studentName"
          input-width="200px"
          description="学生姓名"
        />
      </search-item>
      <search-item>
        <PDInput
          v-model="queryParams.studentMajor"
          input-width="200px"
          description="学生专业"
        />
      </search-item>
      <search-item
        label="单位名称"
      >
        <el-select
          v-model="queryParams.unitId"
          size="mini"
          clearable
          filterable
          @clear="handleClear('unitId')"
        >
          <el-option
            v-for="item in unitList"
            :key="item.unitId"
            :label="item.name"
            :value="item.unitId"
          />
        </el-select>
      </search-item>

      <search-item
        label="实验室"
      >
        <el-select
          v-model="queryParams.labId"
          size="mini"
          clearable
          filterable
          @clear="handleClear('labId')"
        >
          <el-option
            v-for="item in laboratoryList"
            :key="item.labId"
            :label="item.name"
            :value="item.labId"
          />
        </el-select>
      </search-item>

      <search-item label="使用日期">
        <el-date-picker
          v-model="queryParams.usageDate"
          size="small"
          value-format="yyyy-MM-dd"
          align="right"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions"
        />
      </search-item>
    </search-pane>

    <table-tool-bar
      v-model="showSearchPane"
      :hidden-button="['add']"
      @handleCreate="handleCreateDeviceRecord"
      @refresh="fetchDeviceRecordPage"
    />

    <table-card>
      <el-table
        ref="filterTable"
        :data="deviceRecordList"
        style="width: 100%"
      >
        <el-table-column
          prop="usageDate"
          label="使用日期"
        />
        <el-table-column
          prop="studentMajor"
          label="学生专业"
        />
        <el-table-column
          prop="studentName"
          label="学生姓名"
        />

        <el-table-column
          prop="labName"
          label="实验室"
        />

        <el-table-column
          prop="deviceId"
          label="设备编号"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="toDevice(scope.row.deviceId)"
            >
              {{ scope.row.deviceId }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column
          prop="deviceName"
          label="实验设备"
          width="100"
        />

        <el-table-column
          prop="unitName"
          label="单位"
          width="150"
        />

        <el-table-column
          prop="startTime"
          label="开始时间"
        />

        <el-table-column
          prop="endTime"
          label="结束时间"
        />

        <el-table-column
          prop="duration"
          label="使用时长"
        />
        <el-table-column
          label="操作"
          fixed="right"
          width="200"
        >
          <template slot-scope="scope">
            <table-option-group
              type="button"
              @handleDelete="handleDeleteDeviceRecord(scope.row.id)"
              @handleUpdate="handleUpdateDeviceRecord(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="fetchDeviceRecordPage"
      />
    </table-card>

    <form-dialog
      v-model="dialogFormVisible"
      :type="formType"
      @create="createDeviceRecord"
      @update="updateDeviceRecord"
    >
      <el-form
        ref="deviceRecordForm"
        :rules="formRules"
        :model="tempDeviceRecord"
      />
    </form-dialog>
  </div>
</template>

<script>
import SearchPane from '@/components/SearchPane/SearchPane'
import SearchItem from '@/components/SearchPane/SearchItem'
import PDInput from '@/components/SearchPane/PDInput'
import TableCard from '@/components/table/TableCard'
import TableToolBar from '@/components/table/TableToolBar'
import { addDeviceRecord, deleteDeviceRecord, pageDeviceRecords, updateDeviceRecord } from '@/api/device-record'
import FormDialog from '@/components/FormDialog/FormDialog'
import TableOptionGroup from '@/components/table/TableOptionGroup'
import { showSuccessTip } from '@/utils/simple-tips'
import Pagination from '@/components/Pagination'
import { listLaboratories } from '@/api/laboratory'
import { listUnits } from '@/api/unit'

export default {
  name: 'DeviceRecord',
  props: {
    deviceId: {
      type: String,
      default: ''
    }
  },
  components: { Pagination, TableOptionGroup, FormDialog, TableToolBar, TableCard, PDInput, SearchItem, SearchPane },
  data() {
    return {
      // search attr
      showSearchPane: true,
      queryParams: {
        pageSize: 5,
        pageNum: 1
      },
      total: 10,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },

      // form attr
      tempDeviceRecord: {

      },
      dialogFormVisible: false,
      formType: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      formRules: {

      },

      // table attr
      deviceRecordList: [],

      // common attr
      unitList: [],
      laboratoryList: []
    }
  },
  mounted() {
    if (this.deviceId !== ''){
      this.queryParams.deviceId = this.deviceId
    }
    this.fetchDeviceRecordPage()
    this.fetchUnitList()
    this.fetchLaboratoryList()
  },
  methods: {

    fetchDeviceRecordPage() {
      pageDeviceRecords(this.queryParams).then(response => {
        this.deviceRecordList = response.data.list
        this.total = response.data.total
      })
    },
    fetchUnitList() {
      listUnits().then(response => {
        this.unitList = response.data
      })
    },
    fetchLaboratoryList() {
      listLaboratories().then(response => {
        this.laboratoryList = response.data
      })
    },

    // region search relative function
    handleSearchDeviceRecord() {
      this.fetchDeviceRecordPage()
    },
    resetDeviceRecordQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5
      }
    },
    handleClear(param) {
      this.queryParams[param] = undefined
    },
    // endregion

    // region form relative function
    resetTempDeviceRecord() {
      this.tempDeviceRecord = {}
    },
    handleCreateDeviceRecord() {
      this.resetTempDeviceRecord()
      this.formType = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['deviceRecordForm'].clearValidate()
      })
    },
    createDeviceRecord() {
      this.$refs['deviceRecordForm'].validate((valid) => {
        if (valid) {
          addDeviceRecord(this.tempDeviceRecord).then(() => {
            this.fetchDeviceRecordPage()
            this.dialogFormVisible = false
            showSuccessTip()
          })
        }
      })
    },
    handleUpdateDeviceRecord(row) {
      this.tempDeviceRecord = Object.assign({}, row)
      this.formType = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['deviceRecordForm'].clearValidate()
      })
    },
    updateDeviceRecord() {
      this.$refs['deviceRecordForm'].validate((valid) => {
        if (valid) {
          const tempDeviceRecord = Object.assign({}, this.tempDeviceRecord)
          updateDeviceRecord(tempDeviceRecord).then(() => {
            this.fetchDeviceRecordPage()
            this.dialogFormVisible = false
            showSuccessTip()
          })
        }
      })
    },
    handleDeleteDeviceRecord(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDeviceRecord(id).then(() => {
          this.dialogFormVisible = false
          this.fetchDeviceRecordPage()
          showSuccessTip()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // endregion

    // region router relative function
    toDevice(deviceId) {
      this.$router.push({
        name: 'Device',
        params: {
          deviceId: deviceId
        }
      })
    }
    // endregion
  }
}

</script>

<style lang="scss" scoped>
</style>
